package com.speedricemanager.other.base;

import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.jbm.core.iface.IAcross;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.speedricemanager.R;
import com.speedricemanager.activity.home.intface.IntegerFaceOr;
import com.speedricemanager.interfaces.DialogBackListener;
import com.speedricemanager.interfaces.DialogSuccess;
import com.speedricemanager.model.home.OrderModel;
import com.speedricemanager.other.config.Config;
import com.speedricemanager.other.server.KeepService;
import com.speedricemanager.other.server.ServerModel;
import com.speedricemanager.other.utils.TextUtils;
import com.vondear.rxtools.RxActivityUtils;
import com.vondear.rxtools.RxPhotoUtils;
import com.vondear.rxtools.RxSPUtils;
import com.vondear.rxtools.view.RxTitle;
import com.vondear.rxtools.view.RxToast;
import com.vondear.rxtools.view.dialog.RxDialogChooseImage;
import com.vondear.rxtools.view.dialog.RxDialogSureCancel;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import rx.functions.Action1;

import static com.speedricemanager.other.config.Config.SUCCESS;
import static com.vondear.rxtools.view.dialog.RxDialogChooseImage.LayoutType.TITLE;

/**
 *
 *  <com.vondear.rxtools.view.RxTitle
 android:id="@+id/rx_title"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="@color/colorPrimary"
 app:title="RxDataUtils操作Demo"/>

 xmlns:app="http://schemas.android.com/apk/res-auto"


 smallPullLoadMoreRecyclerView.getRecyclerView().addItemDecoration(new DividerItemDecoration(this, 1));

 *
 *
 */
public abstract class BaseAty extends AppCompatActivity implements DialogBackListener,Action1<IAcross> {
    private Uri resultUri;

    private String msg;
    //是否在前台
    private boolean isForgound;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        RxActivityUtils.addActivity(this);
       hiddenPan();


    }
    //隐藏软键盘
    public void hiddenPan() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
    }

    @Override
    protected void onPause() {
        super.onPause();
        isForgound=false;
    }
    @Override
    protected void onResume() {
        super.onResume();
        isForgound=true;
  }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // 点击空白隐藏键盘
        InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (getCurrentFocus() != null) {
                if (getCurrentFocus().getWindowToken() != null) {
                    mInputMethodManager.hideSoftInputFromWindow(
                            getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        }
        return super.onTouchEvent(event);
    }




    //设置toobar
    public void setTitle(RxTitle mRxTitle){
        mRxTitle.setLeftFinish(this);
    }
    public void setTitleRight(RxTitle mRxTitle, String right, View.OnClickListener listener){
        mRxTitle.setLeftFinish(this);
        mRxTitle.setRightText(right);
        mRxTitle.setRightTextVisibility(true);
        mRxTitle.setLeftIconOnClickListener(listener);
        mRxTitle.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showRight();
            }
        });
    }


    public void setTitle(RxTitle mRxTitle,String title){
        mRxTitle.setLeftFinish(this);
        mRxTitle.setTitle(title);
    }

    public void setTitle(RxTitle mRxTitle,int resource){
        mRxTitle.setLeftFinish(this);
        mRxTitle.setRightIconVisibility(true);
        mRxTitle.setRightIcon(resource);
        mRxTitle.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showRight();
            }
        });
    }

    protected void showRight(){

    }
    protected void startActivity(Class end){
        startActivity(new Intent(this,end));
    }

    protected void startActivityForResult(int requestNum,Class end){
        startActivityForResult(new Intent(this,end),requestNum);
    }

    //提示框 带有确定的提示框
    public void showAlert(final DialogSuccess listener, String... data) {
        new QMUIDialog.MessageDialogBuilder(this)
                .setTitle(data[0])
                .setMessage(data[1])
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        if(listener!=null){
                            listener.option("");
                        }
                        dialog.dismiss();
                    }
                })
                .show();
    }


    //提示框 带有确定的提示框
    public void showAlert(final DialogSuccess listener, CharSequence comtent) {
        new QMUIDialog.MessageDialogBuilder(this)
                .setTitle("提示")
                .setMessage(comtent)
               .addAction("取消", new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                dialog.dismiss();
            }
        })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        if(listener!=null){
                            listener.option("");
                        }
                        dialog.dismiss();
                    }
                })
                .show();
    }

    /**
     * 带有红色确定按钮的对话框
     * @param data
     */
    public void showDeleteDialog(final String... data){
        new QMUIDialog.MessageDialogBuilder(this)
                .setTitle(data[0])
                .setMessage(data[1])
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                        fails();
                    }
                })
                .addAction(0, "确定", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                    //    Toast.makeText(BaseAty.this, "删除成功"+index, Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                        success(data[2]);
                    }
                })
                .show();
    }
    private QMUITipDialog tipDialog;
    //加载框
    public void onLoad(){
         tipDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("正在加载")
                .create();
        tipDialog.show();
    }
    public void loadDismiss(){
        if(tipDialog!=null&&tipDialog.isShowing()) {
            tipDialog.dismiss();
        }
    }


private Toast toast;
    //普通消息提示
     public void messageAlert(final String msg1){
         if(!isFinishing()){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                         toast = RxToast.info(BaseAty.this, msg1, Toast.LENGTH_SHORT, true);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                      toast  .show();
                    }
                });
         }
     }
    //错误消息提示
    public void errorAlert(final String error){
        if(!isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    toast = RxToast.error(BaseAty.this, error, Toast.LENGTH_SHORT, true);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast  .show();
                }
            });
        }

    }
    //成功的消息提示
    public void successAlert(final String msg){
        if(!isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
        RxToast.success(BaseAty.this, msg, Toast.LENGTH_SHORT, true).show();
                }
            });
        }
    }

    //商家返回用了   需要抽出来
    public void  commitDialog(String content, final int type){
        new QMUIDialog.MessageDialogBuilder(this)
                .setTitle("提示")
                .setMessage(content)
                .addAction(0, "确定", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, final int index) {
                        switch (type){
                            case 101:
                                //将Cookie发送到商家  1 淘宝 2京东
//                                    final String[] data=msg.split(",");
//                                share.checkSmall(data[1],Integer.parseInt(data[0]+"")==1?false:true, new ShareData.CheckSmallListener() {
//                                    @Override
//                                    public void allow() {
//                                        IAcross icross = ServerModel.getInterface().SendCallback(from_id, "RemotePayResponseToSeller",order_id, share.reMainCookie(share.getCookie(),Integer.parseInt(data[0])-1));
//                                        if(icross.m_code==SUCCESS){
//                                            successAlert("发送成功");
//                                        }else{
//                                            errorAlert(icross.m_info);
//                                        }
//                                    }
//
//                                    @Override
//                                    public void unAllow() {
////                                        Intent intent = new Intent(BaseAty.this, LoginTaoAty.class);
////                                        intent.putExtra("nickName", msg);
////                                        intent.putExtra("order_id",order_id);
////                                        intent.putExtra("from_id",from_id);
////                                        //0 淘宝   1京东    这里需要改   淘宝和京东没有区分
////                                        intent.putExtra("platType",(Integer.parseInt(data[0]+"")-1));
////                                        //0 代表选择了小号进入的  1代表添加小号  2代表商家申请cookie
////                                        intent.putExtra("type", 2);
////                                        startActivity(intent);
//                                    }
//                                });
                                break;
                            case 100:
                                //用于商家取消订单
                                OrderModel model=new OrderModel();
                                model.auditcancelOrderSJ(order_id);
                                break;
                            default:
                                success(type+"");
                                break;
                        }
                        dialog.dismiss();
                    }
                })
                .show().setCancelable(false);
    }



    protected QMUIDialog alert;

    /**
     * @param title
     * @param option
     * @param
     *
     */
    public void editAlert(String title, final DialogSuccess option){
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(this);
        alert = builder.setTitle(title)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        if(!TextUtils.isEmpty(builder.getEditText().getText().toString())){
                            messageAlert("请输入内容");
                            return;
                        }
                        option.option(builder.getEditText().getText().toString());
                       dialog.dismiss();
                    }
                })
                .show();
    }

    protected void editDismiss(){
        if(alert!=null){
            alert.dismiss();
        }

    }

    @Override
    public void finish() {
        hiddenPan();
        loadDismiss();
        super.finish();
//        overridePendingTransition(R.anim.slide_left_in,
//                R.anim.slide_right_out);

    }

    //dialog的回调
    @Override
    public void fails() {

    }

    @Override
    public void success(String type) {

    }


    /**
     * 下面是上传图片   通过相机和相册
     */
    public void selectPhoto() {
        Resources r = getResources();
        resultUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + r.getResourcePackageName(R.mipmap.pic) + "/"
                + r.getResourceTypeName(R.mipmap.pic) + "/"
                + r.getResourceEntryName(R.mipmap.pic));
        RxDialogChooseImage dialogChooseImage = new RxDialogChooseImage(this, TITLE);
        dialogChooseImage.show();
    }
    private ImageView img;
    public void setIma(ImageView img1){
        img=img1;
    }

    public File getRect() {
        return rect;
    }
    //返回的是方形的  不需要裁剪
    private File rect;
    //false 代表 相册 true 代表摄像机
    protected boolean isVidicon;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case RxPhotoUtils.GET_IMAGE_FROM_PHONE://选择相册之后的处理
                if (resultCode == RESULT_OK) {
//                    RxPhotoUtils.cropImage(ActivityUser.this, );// 裁剪图片
                    if(null == img) {//裁剪
                        initUCrop(data.getData());
                    }else{ //不裁剪
                        isVidicon=false;
                        rect=roadImageView(data.getData()+"");
                        if(rect.length()!=0) {
//                                Glide.with(this).
//                                        load(data.getData()).
//                                        diskCacheStrategy(DiskCacheStrategy.RESULT).
////                            bitmapTransform(new CropCircleTransformation(this)).
//                                        thumbnail(0.5f).
//                                        placeholder(R.mipmap.pic).
//                                        priority(Priority.LOW).
//                                        error(R.mipmap.pic).
//                                        fallback(R.mipmap.pic).
//                                        dontAnimate().
//                                        into(img);

                        }

                    }

                }

                break;
            case RxPhotoUtils.GET_IMAGE_BY_CAMERA://选择照相机之后的处理
                if (resultCode == RESULT_OK) {
                   /* data.getExtras().get("data");*/
//                    RxPhotoUtils.cropImage(ActivityUser.this, RxPhotoUtils.imageUriFromCamera);// 裁剪图片
                    if(null == img) {
                        initUCrop(RxPhotoUtils.imageUriFromCamera);
                    }else {
                        isVidicon=true;
//                        Glide.with(this).
//                                load(RxPhotoUtils.imageUriFromCamera).
//                                diskCacheStrategy(DiskCacheStrategy.RESULT).
////                            bitmapTransform(new CropCircleTransformation(this)).
//                                thumbnail(0.5f).
//                                placeholder(R.mipmap.pic).
//                                priority(Priority.LOW).
//                                error(R.mipmap.pic).
//                                fallback(R.mipmap.pic).
//                                dontAnimate().
//                                into(img);
                        rect=roadImageView(RxPhotoUtils.imageUriFromCamera+"");

                    }
                }

                break;
            case RxPhotoUtils.CROP_IMAGE://普通裁剪后的处理
//                Glide.with(this).
//                        load(RxPhotoUtils.cropImageUri).
//                        diskCacheStrategy(DiskCacheStrategy.RESULT).
//                        bitmapTransform(new CropCircleTransformation(this)).
//                        thumbnail(0.5f).
//                        placeholder(R.mipmap.pic).
//                        priority(Priority.LOW).
//                        error(R.mipmap.pic).
//                        fallback(R.mipmap.pic).
//                        dontAnimate().
//                        into(img);
//                RequestUpdateAvatar(new File(RxPhotoUtils.getRealFilePath(mContext, RxPhotoUtils.cropImageUri)));
                break;

            case UCrop.REQUEST_CROP://UCrop裁剪之后的处理
                if (resultCode == RESULT_OK) {
                    resultUri = UCrop.getOutput(data);
//                    roadImageView(resultUri, img);
                    //将图片返回
                    data.putExtra("file",resultUri.toString());
                    /**
                     *    if(resultCode==RESULT_OK){
                     if(data==null){
                     return;
                     }

                     */

                    setResult(RESULT_OK,data);
                    RxSPUtils.putContent(this, "AVATAR", resultUri.toString());
                } else if (resultCode == UCrop.RESULT_ERROR) {
                    final Throwable cropError = UCrop.getError(data);
                }
                break;
            case UCrop.RESULT_ERROR://UCrop裁剪错误之后的处理
                final Throwable cropError = UCrop.getError(data);
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //从Uri中加载图片 并将其转化成File文件返回
    public File roadImageView(String uri1, ImageView imageView) {
        Uri uri = Uri.parse(uri1);
//        Glide.with(this).
//                load(uri).
//                diskCacheStrategy(DiskCacheStrategy.RESULT).
//                bitmapTransform(new CropCircleTransformation(this)).
//                thumbnail(0.5f).
//                placeholder(R.mipmap.pic).
//                priority(Priority.LOW).
//                error(R.mipmap.pic).
//                fallback(R.mipmap.pic).
//                dontAnimate().
//                into(imageView);

        return (new File(RxPhotoUtils.getImageAbsolutePath(this, uri)));
    }
    public File roadImageView(String uri) {
        return (new File(RxPhotoUtils.getImageAbsolutePath(this, Uri.parse(uri))));
    }

    private void initUCrop(Uri uri) {
        //Uri destinationUri = RxPhotoUtils.createImagePathUri(this);
        SimpleDateFormat timeFormatter = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
        long time = System.currentTimeMillis();
        String imageName = timeFormatter.format(new Date(time));

        Uri destinationUri = Uri.fromFile(new File(getCacheDir(), imageName + ".jpeg"));

        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置隐藏底部容器，默认显示
        //options.setHideBottomControls(true);
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(this, R.color.colorPrimary));
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(this, R.color.colorPrimaryDark));

        //开始设置
        //设置最大缩放比例
        options.setMaxScaleMultiplier(5);
        //设置图片在切换比例时的动画
        options.setImageToCropBoundsAnimDuration(666);
        //设置裁剪窗口是否为椭圆
//        options.setOvalDimmedLayer(true);
        //设置是否展示矩形裁剪框
//        options.setShowCropFrame(false);
        //设置裁剪框横竖线的宽度
//        options.setCropGridStrokeWidth(20);
        //设置裁剪框横竖线的颜色
//        options.setCropGridColor(Color.GREEN);
        //设置竖线的数量
//        options.setCropGridColumnCount(2);
        //设置横线的数量
//        options.setCropGridRowCount(1);
        UCrop.of(uri, destinationUri)
                .withAspectRatio(1, 1)
                .withMaxResultSize(1000, 1000)
                .withOptions(options)
                .start(this);
    }

private  int order_id,from_id;

    /**
     * 请求接口完成回调
     * @param iAcross
     * @param methodName
     */
     protected   void onComplete(IAcross iAcross, String methodName){};
    protected  void onExe(){};
    private boolean isExit;
    @Override
    public void call(IAcross iAcross) {
        loadDismiss();
        onExe();
        if(SUCCESS == iAcross.m_code){
            Config.CONNECT=0;
            onComplete(iAcross,iAcross.method);
        }else{
            if(iAcross.m_code==400){
                //重新连接
                ServerModel.getInterface().Disconnect(true);
                startService(new Intent(getApplicationContext(), KeepService.class));
                Config.CONNECT=0;
            }
            if(iAcross.m_code==408){
                //请求超时
                Config.CONNECT+=1;
            }
            if("Logout".equals(iAcross.method)){
                return;
            }
            errorAlert(iAcross.m_info);
            onError(iAcross,iAcross.method);
        }
    }

    /**
     * 请求接口错误回调
     * @param iAcross
     * @param methodName
     */
    protected void onError(IAcross iAcross, String methodName) {

    }

    @Override
    protected void onDestroy() {

        System.gc();
        RxActivityUtils.finishActivity(this);
        loadDismiss();
        super.onDestroy();
//
    }


public void getLoadDialog(final String str[], final IntegerFaceOr ic){
    new QMUIDialog.MenuDialogBuilder(this)
            .addItems(str, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, final int which) {
                    ic.getSucces(which);
                    dialog.dismiss();
                }
            }).show();
}

    public void editAlerts(String title, final DialogSuccess option) {
        final RxDialogSureCancel rxDialogSureCancel = new RxDialogSureCancel(this);
        View view = View.inflate(this, R.layout.rejisterlistview, null);
        rxDialogSureCancel.setContentView(view);
        ListView listview = view.findViewById(R.id.listview);
        TextView canceldia = view.findViewById(R.id.canceldia);
        TextView commitdia = view.findViewById(R.id.commitdia);

        canceldia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rxDialogSureCancel.dismiss();
            }
        });

        commitdia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                option.option("");

                rxDialogSureCancel.dismiss();
            }
        });
        rxDialogSureCancel.show();

    }
}
